package cn.youframe.comp.tree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * User: Administrator
 * DateTime: 13-3-13 下午8:41
 * Desc:
 */
public class Tree<T extends INode>{
    private String treeName;
    private TreeNode<T> root;//根节点
    public Tree() {
    }
    /**
     * findNode 查询树中的节点
     *
     * @param nodeID String
     * @return TreeNode
     */
    public TreeNode<T> findNode(String nodeID) {
        return findNode(getRoot(),nodeID);
    }

    /**
     * findNode 查询树中指定节点下的节点
     *
     * @param treeNode TreeNode
     * @param nodeID String
     * @return TreeNode
     */
    public TreeNode<T> findNode(TreeNode<T> treeNode, String nodeID) {
        if (treeNode.getNodeID().equals(nodeID)) {
            return treeNode;
        }
        Iterator children = treeNode.getChildren().iterator();
        while (children.hasNext()) {
            TreeNode<T> child = (TreeNode<T>)children.next();
            TreeNode<T> match = findNode(child, nodeID);
            if (match != null) {
                return match;
            }
        }
        return null;
    }

    /**
     * getNodeList 按树状顺序得到List列表
     *
     * @return List
     */
    private List<T> nodeList=null;
    public synchronized List<T> getNodeList() {
        nodeList=new ArrayList<T>();
        listNodes(this.getRoot());
        return nodeList;
    }
    /**
     * listNodes 查询树中指定节点下的节点
     *
     * @param treeNode TreeNode
     * @return void
     */
    public void listNodes(TreeNode<T> treeNode) {
        if (treeNode != null) {
            nodeList.add(treeNode.getNodeObj());
            if (treeNode.getChildren() != null) {
                Iterator children = treeNode.getChildren().iterator();
                TreeNode<T> child =null;
                while (children.hasNext()) {
                    child = (TreeNode<T>) children.next();
                    listNodes(child);
                }
            }
        }
    }
    public void setRoot(TreeNode<T> root) {
        this.root = root;
    }

    public void setTreeName(String treeName) {
        this.treeName = treeName;
    }

    public TreeNode<T> getRoot() {
        return root;
    }

    public String getTreeName() {
        return treeName;
    }
}
